from pprint import pprint

from django.http import JsonResponse
from django.shortcuts import render
import sqlite3
import json
from django.views.decorators.csrf import csrf_exempt

from process.dbpath import db_path
import os
# Create your views here.
'''
AllIn
Transform
UserBuy
platformActiveHour
platformActive
'''


def index(request):
    return render(request, 'index.html')


@csrf_exempt
def UserType(request):
    response = {}

    # hotpie 是一个各种物品的rank buypie同理， Allin是总rank可以把其他归为other

    userId = json.loads(request.body.decode('utf-8'))['userId']

    conn = sqlite3.connect("./db.sqlite3")
    # print(conn)
    print('Opened database successfully')
    cu = conn.cursor()
    print("cursor successfully")
    # cu.execute(r'select * from UserType where userId = "100"')
    cu.execute(r'select * from UserType where userId = "' + userId + '"')
    print("select successfully")

    data = eval(cu.fetchall()[0][1])

    try:
        h1 = [a[0] for a in data['hotPie']][:5]  # keys
        h2 = [a[1] for a in data['hotPie']][:5]  # values
        h3 = [a[0] for a in data['buyPie']][:5]
        h4 = [a[1] for a in data['buyPie']][:5]
    except:
        h1 = [a[0] for a in data['hotPie']]  # keys
        h2 = [a[1] for a in data['hotPie']]  # values
        h3 = [a[0] for a in data['buyPie']]
        h4 = [a[1] for a in data['buyPie']]
    hotPie_data = []
    buyPie_data = []
    for a, b in zip(h1, h2):
        hotPie_data.append({"value": b, "name": a})
    for a, b in zip(h3, h4):
        buyPie_data.append({"value": b, "name": a})

    print(h1)
    print(hotPie_data)
    print(h3)
    print(buyPie_data)
    response['hotPie_keys'] = h1
    response['hotPie_data'] = hotPie_data
    response['buyPie_keys'] = h3
    response['buyPie_data'] = buyPie_data

    conn.close()
    return JsonResponse(response, json_dumps_params={"ensure_ascii": False})


@csrf_exempt
def User(request):
    response = {}

    lst = ['2017-11-25', '2017-11-26', '2017-11-27', '2017-11-28', '2017-11-29', '2017-11-30', '2017-12-01',
           '2017-12-02', '2017-12-03']
    lst = {a: 0 for a in lst}
    print(lst)
    # 是用户每天在平台上的一个活跃度
    userId = json.loads(request.body.decode('utf-8'))['userId']
    conn = sqlite3.connect("./db.sqlite3")
    # print(conn)
    print('Opened database successfully')
    cu = conn.cursor()
    print("cursor successfully")
    # cu.execute(r'select * from User where userId = "1"')
    cu.execute(r'select * from User where userId = "' + userId + '"')
    print("select successfully")
    # print(cu.fetchall())
    data = eval(cu.fetchall()[0][1])
    print(data)
    for keys, value in data.items():
        try:
            lst[keys] = value
        except:
            continue
    keys = list(lst.keys())  # keys
    values = [round(a, 3) for a in list(lst.values())]  # values
    print(keys)
    print(values)
    response['keys'] = keys
    response['values'] = values
    conn.close()
    return JsonResponse(response, json_dumps_params={"ensure_ascii": False})


def get_all_count(req):
    resp = {}
    conn = sqlite3.connect("./data.db")
    cur = conn.cursor()
    cur.execute("select info from  tmp where id = 'LineData';")
    tmp = cur.fetchone()[0]
    resp['line'] = eval(tmp)
    cur.execute("select info from tmp where id = 'PanelData';")
    tmp = cur.fetchone()[0]
    resp['panel'] = eval(tmp)
    return JsonResponse(resp, json_dumps_params={'ensure_ascii': False})


# 做个饼图，展示热度前十的商品类型
def get_pie_info(req):
    resp = {}
    conn = sqlite3.connect("./data.db")
    cur = conn.cursor()
    cur.execute("select info from tmp where id = 'TopPieData';")
    tmp = cur.fetchone()[0]
    resp['data'] = eval(tmp)
    return JsonResponse(resp, json_dumps_params={'ensure_ascii': False})


def get_one_type(req):
    resp = {}
    conn = sqlite3.connect("./data.db")
    cur = conn.cursor()
    cur.execute("select info from tmp where id = 'all_type';")
    tmp = cur.fetchone()[0]
    tmp = list(eval(tmp))
    resp['type'] = []
    if len(tmp) != 0:
        resp['type'].append({'label': tmp[0], 'name': tmp[0]})
    return JsonResponse(resp, json_dumps_params={'ensure_ascii': False})


def query_type(request):
    resp = {}
    conn = sqlite3.connect("./data.db")
    cur = conn.cursor()
    s = request.GET.get('param', default='')
    if s == '':
        resp['types'] = []
    else:
        sql = "select id from ItemInfo where id like '%" + s + "%'"
        cur.execute(sql)
        res = cur.fetchall()
        res = list(res)
        if len(res) > 100:
            resp['types'] = sorted(res)[0:100]
        else:
            resp['types'] = res

    return JsonResponse(resp, json_dumps_params={'ensure_ascii': False})


def query_item_info(request):
    resp = {}
    conn = sqlite3.connect("./data.db")
    cur = conn.cursor()
    s = request.GET.get('param', default='')
    print(s)
    if s == '':
        resp['data'] = []
    else:
        sql = "select data from ItemInfo where id = '%s'" % s
        cur.execute(sql)
        tmp = cur.fetchone()[0]
        tmp = eval(tmp)
        res = []
        if type(tmp) == dict:
            _item = {}
            for i in tmp.keys():
                _item.update({'name': i})
                _item.update(tmp.get(i))
                _item['sum'] = round(_item['sum'], 2)
                res.append(_item)
        else:
            for item in tmp:
                _item = {}
                _item.update({'name': item[0]})
                _item.update(item[1])
                _item['sum'] = round(_item['sum'], 2)
                res.append(_item)

        resp['data'] = res

    return JsonResponse(resp, json_dumps_params={'ensure_ascii': False})

#
@csrf_exempt
def getrec(request):
    response = {}

    # 推荐
    userId = json.loads(request.body.decode('utf-8'))['userId']
    conn = sqlite3.connect("./rec.sqlite3")
    print('Opened database successfully')
    cu = conn.cursor()
    print("cursor successfully")
    # cu.execute(r'select * from User where userId = "1"')
    cu.execute(r'select * from rec where userId = "' + userId + '"')
    print("select successfully")
    data = eval(cu.fetchall()[0][1])
    # print(data)

    rec_keys = [a[0] for a in data]
    rec_values = [a[1] for a in data]
    # print(rec_keys)
    # print(rec_values)

    response['rec_keys'] = rec_keys
    response['rec_values'] = rec_values

    rec = []
    for a, b in zip(rec_keys, rec_values):
        rec.append({"itemId": a, "hot": b})

    print(rec)
    response['rec'] = rec

    conn.close()
    return JsonResponse(response, json_dumps_params={"ensure_ascii": False})
